package org.bot.server.socket.impl;

import org.bot.server.client.service.BotClientSocketDriveService;
import org.springframework.http.HttpHeaders;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: 沧月
 * @Date: 2023/12/16 20:38
 * @Description: 描述
 */
public class ServerClientAuth {

    HttpHeaders headers;
    WebSocketSession session;
    ServerWebSocket webSocket;

    public ServerClientAuth(WebSocketSession session, ServerWebSocket webSocket) {
        headers = session.getHandshakeHeaders();
        this.session = session;
        this.webSocket = webSocket;
    }

    public String auth(BotClientSocketDriveService botClientService) throws IOException {
        String clientId = this.getHeader(AuthMessage.CODE_4031, AuthKV.CLIENT_ID.value);
        String secretKey = this.getHeader(AuthMessage.CODE_4032, AuthKV.SECRET_KEY.value);
        String mac = this.getHeader(AuthMessage.CODE_4033, AuthKV.MAC.value);

        if (clientId == null) {
            webSocket.closeClient(session, AuthMessage.CODE_4031);
        }

        Map<String, Object> flowInfo = botClientService.getClientInfo(clientId);
        if (flowInfo == null || flowInfo.isEmpty()) {
            webSocket.closeClient(session, AuthMessage.CODE_4308);
        }

        if (flowInfo.get(AuthKV.SECRET.value) == null || !flowInfo.get(AuthKV.SECRET.value).equals(secretKey)) {
            webSocket.closeClient(session, AuthMessage.CODE_4304);
        }

        Integer activateStatus = (Integer) flowInfo.get(AuthKV.ACTIVATE_STATUS.value);
        if (activateStatus == 1) {
            //已激活需要验证mac
            if (!Objects.equals(flowInfo.get(AuthKV.DEVICE_ID.value).toString(), mac)) {
                webSocket.closeClient(session, AuthMessage.CODE_4306);
            }
        } else {
            botClientService.updateMac(Integer.parseInt(flowInfo.get("id").toString()), mac);
        }
        return clientId;
    }


    private String getHeader(AuthMessage message, String key) throws IOException {
        List<String> list = this.headers.get(key);
        if (list != null && list.isEmpty()) {
            webSocket.closeClient(session, message);
        }
        return list.get(0);
    }
}
